package com.boco.fznq.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.boco.fznq.AppConstants;
import com.boco.fznq.R;
import com.boco.fznq.login.bean.BaseBean;
import com.boco.fznq.login.bean.UserBean;
import com.boco.fznq.main.MainActivity;
import com.boco.fznq.network.HttpListener;
import com.boco.fznq.network.HttpUtils;
import com.boco.fznq.utils.SPKey;
import com.boco.fznq.utils.SPUtils;
import com.culiu.core.activity.BaseCoreActivity;
import com.culiu.core.utils.notification.ToastUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.OnSendMessageHandler;
import cn.smssdk.SMSSDK;

/**
 * Created by jiangcheng on 2017/8/30.
 */

public class RegisterActivity extends BaseCoreActivity {

    public static final int FORGET_PAGE = 0x12;

    public static final int REGISTER_PAGE = 0x13;

    @BindView(R.id.logo)
    ImageView mLogo;
    @BindView(R.id.phone)
    EditText mPhone;
    @BindView(R.id.password)
    EditText mPassword;
    @BindView(R.id.password_tips)
    TextView mPasswordTips;
    @BindView(R.id.confim_password)
    EditText mConfimPassword;
    @BindView(R.id.phone_verify_et)
    EditText mPhoneVerifyEt;
    @BindView(R.id.phone_verify)
    Button mPhoneVerify;
    @BindView(R.id.confirm)
    Button mConfirm;

    private String phone;
    private String password;
    private String confirmPwd;
    private String verifyCode;

    private SendSmsCodeCountDown mSmsCodeController;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        initViews();
    }

    private void initViews() {
        SMSSDK.registerEventHandler(eventHandler); //注册短信回调
        if (mSmsCodeController == null) {
            mSmsCodeController = new SendSmsCodeCountDown(mPhoneVerify);
        }
        mSmsCodeController.stopCountDown();
    }

    @Override
    public void showLoadingDialog() {

    }

    @Override
    public void dismissLoadingDialog() {

    }

    @OnClick({R.id.phone_verify, R.id.confirm})
    public void onViewClicked(View view) {
        phone = mPhone.getText().toString();
        password = mPassword.getText().toString();
        confirmPwd = mConfimPassword.getText().toString();

        switch (view.getId()) {
            case R.id.phone_verify:
                sendPhoneVerifyCode();
                break;
            case R.id.confirm:
                if (!checkPhoneAndPwd()) {
                    return;
                }

                SMSSDK.submitVerificationCode("86", phone, mPhoneVerifyEt.getText().toString());
                break;
        }
    }

    /**
     * 发送短信验证码
     */
    private void sendPhoneVerifyCode() {
        if (checkPhoneAndPwd()) {
            SMSSDK.getVerificationCode("86", phone, new OnSendMessageHandler() {
                @Override
                public boolean onSendMessage(String s, String s1) {
                    return false;
                }
            });
        }
    }


    /**
     * 检查电话和密码
     *
     * @return
     */
    private boolean checkPhoneAndPwd() {
        String phoneTips = VerifyUtil.verifyPhone(phone);
        String passwordTips = VerifyUtil.verifyPasswordEquals(password, confirmPwd);

        if (!TextUtils.isEmpty(phoneTips)) {
            ToastUtils.showShort(this, phoneTips);
        } else if (!TextUtils.isEmpty(passwordTips)) {
            ToastUtils.showShort(this, passwordTips);
        } else {
            return true;
        }
        return false;
    }


    private EventHandler eventHandler = new EventHandler() {

        @Override
        public void afterEvent(int event, int result, Object data) {

            if (result == SMSSDK.RESULT_COMPLETE) {
                //回调完成
                Log.d("jiangcheng", "回调完成");

                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    //提交验证码成功
                    register();
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    //获取验证码成功
                    mSmsCodeController.startCountDown();
                } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                    //返回支持发送验证码的国家列表

                } else if (event == SMSSDK.RESULT_ERROR) {
                    ToastUtils.showShort(RegisterActivity.this, "验证码错误!");
                }
            } else {
                ((Throwable) data).printStackTrace();
            }
        }
    };

    /**
     *
     */
    private void register() {
        /**
         * 注册的url
         */
        final String registerUrl = AppConstants.HOST + "/api/register";

        HttpUtils.post(registerUrl, CommonParams.getRegisterParams(phone, password),
                BaseBean.class, new HttpListener<BaseBean>() {
                    @Override
                    public void onResponse(BaseBean response) {
                        mConfirm.setClickable(true);
                        if (response != null && response.isSuccess()) {
                            autoLogin(phone, password);
                        } else {
                            ToastUtils.showShort(RegisterActivity.this, response.getMsg());
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        mConfirm.setClickable(true);
                    }
                });
        mConfirm.setClickable(false);
    }



    /**
     * 自动登陆
     *
     * @param username
     * @param password
     */
    private void autoLogin(String username, String password) {

        String loginUrl = AppConstants.HOST + "/api/login";

        HttpUtils.post(loginUrl, CommonParams.getLoginParams(username, password),
                UserBean.class, new HttpListener<UserBean>() {
                    @Override
                    public void onResponse(UserBean response) {
                        if (response != null && response.isSuccess()) {
                            ToastUtils.showShort(RegisterActivity.this, "登陆成功");

                            if (response.getData() != null) {
                                handleLoginSuccess(response.getData());
                            }
                        } else {
                            ToastUtils.showShort(RegisterActivity.this, response.getMsg());
                        }
                    }

                    @Override
                    public void onError(Exception e) {

                    }
                });

    }

    private void handleLoginSuccess(UserBean.UserInfo data) {
        SPUtils.put(this, SPKey.TOKEN, data.getToken());
        SPUtils.put(this, SPKey.PHONE, data.getPhoneNum());
        SPUtils.put(this, SPKey.HEADERIMG, data.getAvatarUrl());
        org.greenrobot.eventbus.EventBus.getDefault().post(new LoginEvent(data));

        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);

    }


    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterEventHandler(eventHandler);
    }
}
